package com.fancon.rage.comic.json.rpc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.arnx.jsonic.JSONException;

import com.fancon.rage.comic.cache.CacheController;
import com.fancon.rage.comic.dao.PhotoJsonDao;
import com.fancon.rage.comic.entity.PhotoJson;
import com.fancon.rage.comic.entity.RMessage;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;

@SuppressWarnings("serial")
public class RageCollectRpcJsonServlet extends RageBaseService {
	protected PhotoJsonDao jsondao = new PhotoJsonDao();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setHeader("Content-Encoding", "utf-8");
		String action = req.getParameter("action");
		if ("json".equals(action)) {
			int page = Integer.parseInt(req.getParameter("page").replace("_",
					"")); // WTF?
			showPage(page, req, resp);
		} else if ("all".equals(action)) {
			String country = req.getParameter("mode");
			if (country != null && country.length() > 0) {
				showAll(req, resp, country);
			} else {
				showAll(req, resp, null);
			}
		} else if ("numpage".equals(action)) {

		} else if ("notification".equals(action)) {
			showNotification(req, resp);
		} else {
			// show all
			showAll(req, resp, null);
		}

	}

	private void showNotification(HttpServletRequest req,
			HttpServletResponse resp) {
		RMessage mess = new RMessage("true",
				"<b>1883</b><br/>Some stuff happened");
		PrintWriter out = null;
		try {
			out = resp.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.print(encode(mess));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void showPage(int page, HttpServletRequest req,
			HttpServletResponse resp) {

	}

	/**
	 * Get result in cache if not query in database
	 * 
	 * @param req
	 * @param resp
	 * @param mode
	 */
	private void showAll(HttpServletRequest req, HttpServletResponse resp,
			String mode) {
		String modeStr = (mode == null) ? "" : mode;
		ArrayList<PhotoJson> comics = new ArrayList<PhotoJson>();
		String jsonCached = (String) CacheController
				.get("rage_" + modeStr);
		if (jsonCached == null) {
			if (mode == null) {
				comics = (ArrayList<PhotoJson>) jsondao.getAll(1000, 0);
				//comics = getAllPhotoByCountry(null);
			} else {
				comics = (ArrayList<PhotoJson>) jsondao.listByProperty(
						"countryCode", mode, 1000, 0);
				//comics = getAllPhotoByCountry(mode);
			}
			if (comics.size() > 0) {
				try {
					Collections.reverse(comics);
					jsonCached = encode(comics);
					CacheController.put("rage_" + modeStr, jsonCached);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				jsonCached = "[]";
			}
		} else {
		}
		PrintWriter out = null;
		try {
			out = resp.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.print(jsonCached);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private List<Entity> getAllPhotoByCountry(String contryCode){
		// Construct then prepare your query
		  DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		  Query q = new Query("PhotoJson");
		  if(contryCode != null){
		  q.addFilter("countryCode", FilterOperator.EQUAL, contryCode);
		  }
		  q.addSort("id", SortDirection.DESCENDING);
		  PreparedQuery pq = ds.prepare(q);
		  return  pq.asList(FetchOptions.Builder.withLimit(1000).offset(0));
	}
	private void numPage(HttpServletRequest req, HttpServletResponse resp) {

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}
}
